题目:
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
思路:
类似快速排序的思想,只是需要采用三个指针来将数组自然的划分为三份。题目:
class Solution {
public:
void sortColors(int A[], int n) {
int r = -1;
int b = n;
for(int i = 0; i < b; i++){
if(A[i] == 0){
swap(A, ++r, i);
}
else if(A[i] == 2){
swap(A, --b, i);
i--;
}
}
}
void swap(int A[], int x, int y){
int tmp = A[x];
A[x] = A[y];
A[y] = tmp;
}
};